package com.motu.monstercity.server.game.logic;

import com.motu.data.MotuAdManager;
import com.motu.data.MotuBiManager;
import com.motu.data.UserLoginDevice;
import com.motu.monstercity.module.common.iap.Iap;
import com.motu.monstercity.module.common.iap.IapGift;
import com.motu.monstercity.module.common.iap.IapGiftPush;
import com.motu.monstercity.module.common.network.ResponseUtils;
import com.motu.monstercity.module.common.utility.ServerParam;
import com.motu.monstercity.protocol.CmdEnum;
import com.motu.monstercity.protocol.Common.PBIapResult;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameIap;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.act.Act;
import com.motu.monstercity.server.game.commondata.act.ActConstant;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.iap.IapDiamond;
import com.motu.monstercity.server.game.commondata.iap.PrivilegeCard;
import com.motu.monstercity.server.game.commondata.iap.PrivilegeCardConstant;
import com.motu.monstercity.server.game.commondata.iap.Vip;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.union.UnionScuffleGift;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.log.ThinkingDataManager;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.base.PayTypeEnum;
import com.motu.vertx.module.utility.logsdk.AdjustManager;
import com.motu.vertx.module.utility.logsdk.ReyunManager;
import com.motu.vertx.module.utility.logsdk.ToutiaoManager;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class GameIapManager {
    public static final int HTTP_REQUEST_TIMEOUT = 5000;// http请求超时时间(毫秒)

    // 充值购买方式
    public static final int IAP_BUY_TYPE_PAY = 0;// 付费
//    public static final int IAP_BUY_TYPE_PAY_GIFT = 1;// 付费代金券
//    public static final int IAP_BUY_TYPE_FREE_GIFT = 2;// 免费代金券
    public static final int IAP_BUY_TYPE_PAY_PRICE = 3;// 付费代币
    public static final int IAP_BUY_TYPE_FREE_PRICE = 4;// 免费代币
    public static final int IAP_BUY_TYPE_MOTU_MONEY = 5;// 魔兔币

    private static Logger logger = LoggerFactory.getLogger(GameIapManager.class);

    /**
     * 触发推送礼包
     */
    public static void checkTriggerIapGiftPush(UserInfo userInfo, int type, int param) {
        long userId = userInfo.getId();
//        if (!userInfo.checkModuleOpen(SystemOpen.MODULE_ID_IAP_GIFT_PUSH, 0)) {
//            return;
//        }
        List<IapGiftPush> iapGiftPushList = IapManager.getIapGiftPushMainList(type);
        if (iapGiftPushList == null || iapGiftPushList.isEmpty()) {
            return;
        }
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        List<UserIapGiftPush> userIapGiftPushList = GameUser.getUserIapGiftPushList(userId);
        long curTime = TimeUtils.getCurTime();
        for (IapGiftPush iapGiftPush : iapGiftPushList) {
            if (iapGiftPush.getType() != type) {
                continue;
            }
            IapGift iapGift = IapManager.getIapGift(iapGiftPush.getIapGiftId());
            if (iapGift == null || iapGift.getType() != IapGift.TYPE_PUSH || iapGift.getDuration() <= 0) {
                continue;
            }
            List<Integer> paramList = iapGiftPush.getParamList();
            if (paramList.isEmpty()) {
                continue;
            }
            UserIapGiftPush userIapGiftPush = null;
            for (UserIapGiftPush model : userIapGiftPushList) {
                if (model.getIapGiftId() == iapGift.getId()) {
                    userIapGiftPush = model;
                    break;
                }
            }
            // 条件不符合
            if (!isAddUpIapGiftPush(type) && type != IapGiftPush.TYPE_ACT) {
                if (param != paramList.get(0)) {
                    continue;
                }
            }
            // 超过限制推送次数
            if (iapGiftPush.getMainLimitNum() > 0
                    && userIapGiftPush != null
                    && userIapGiftPush.getMainTriggerNum() >= iapGiftPush.getMainLimitNum()) {
                continue;
            }
            // 超过限制购买次数
            if (iapGiftPush.getBuyNum() > 0
                    && userIapGiftPush != null
                    && userIapGiftPush.getBuyNum() >= iapGiftPush.getBuyNum()) {
                continue;
            }
            // 不在累计充值范围内
            List<Integer> chargeNumList = iapGiftPush.getChargeNumList();
            if (chargeNumList.size() >= 2) {
                if (userExtInfo.getIapBuy() < chargeNumList.get(0)
                        || userExtInfo.getIapBuy() > chargeNumList.get(1)) {
                    continue;
                }
            }
//            // 没有购买过特定礼包
//            List<Integer> otherNumList = iapGiftPush.getOtherNumList();
//            if (otherNumList.size() >= 2) {
//                UserIapGiftPush otherUserIapGiftPush = GameUser.getUserIapGiftPush(userId, otherNumList.get(0));
//                if (otherUserIapGiftPush == null || otherUserIapGiftPush.getBuyNum() < otherNumList.get(1)) {
//                    continue;
//                }
//            }
            // 触发之后的特定时间内不可再触发
            if (userIapGiftPush != null && userIapGiftPush.getEndTime() != 0) {
                long triggerTime = userIapGiftPush.getEndTime() - iapGift.getDuration();
                if (triggerTime + iapGiftPush.getIntervalTime() * TimeUtils.MINUTE > curTime) {
                    continue;
                }
            }
            // 达到每日触发次数上限
            if (userIapGiftPush != null && iapGiftPush.getTriggerNum() > 0
                    && userIapGiftPush.getTriggerNumDay() >= iapGiftPush.getTriggerNum()) {
                continue;
            }
            // 不满足触发等级
            if (iapGiftPush.getLimitLevel() > 0 && userInfo.getLevel() < iapGiftPush.getLimitLevel()) {
                continue;
            }
            if (userIapGiftPush == null) {
                userIapGiftPush = new UserIapGiftPush(userId, iapGift.getId());
                userIapGiftPush.doCreate();
                userIapGiftPushList.add(userIapGiftPush);
            }
            // 推送期间的触发次数限制
            if (iapGiftPush.getPushNum() > 0) {
                if (userIapGiftPush.getPushTriggerNum() >= iapGiftPush.getPushNum()) {
                    userIapGiftPush.update();
                    continue;
                }
                userIapGiftPush.addPushTriggerNum(1);
            }
            // 触发推送随机礼包
            if (iapGiftPush.getParam2().length() >= 2) {
//                userIapGiftPush.update();
//                int iapGiftId = getRandomIapGiftId(userInfo, userExtInfo, userIapGiftPushList,
//                        iapGiftPush.getParam2List());
//                if (iapGiftId == 0) {
//                    continue;
//                }
//                userIapGiftPush = null;
//                for (UserIapGiftPush model : userIapGiftPushList) {
//                    if (model.getIapGiftId() == iapGiftId) {
//                        userIapGiftPush = model;
//                        break;
//                    }
//                }
//                if (userIapGiftPush == null) {
//                    userIapGiftPush = new UserIapGiftPush(userId, iapGiftId);
//                    userIapGiftPush.doCreate();
//                    userIapGiftPushList.add(userIapGiftPush);
//                }
//                // 推送期间的触发次数限制
//                if (iapGiftPush.getPushNum() > 0) {
//                    userIapGiftPush.addPushTriggerNum(1);
//                }
            }
            userIapGiftPush.addMainTriggerNum(1);
            userIapGiftPush.putEndTime(curTime + iapGift.getDuration());
            userIapGiftPush.addTriggerNum(1);
            userIapGiftPush.addTriggerNumDay(1);
//            userIapGiftPush.putCauseId(0);
//            userIapGiftPush.putRepeatedType(0);
//            userIapGiftPush.putParam(0);
            userIapGiftPush.putBuyList("");
            userIapGiftPush.update();
            // 数数SDK触发推送礼包事件
//            userTeam = TeamManager.getUserTeam(userId, UserTeam.TYPE_DEFAULT_PVE);
//            long power = userTeam == null ? 0 : userTeam.getPower();
//            ThinkingDataManager.pushPushboxTrigger(userId, userExtInfo.getDistinctId(),
//                    userInfo.getLevel(), userInfo.getVip(), userInfo.getVipScore(), userInfo.getDiamond(),
//                    userInfo.getVipGiftScore(), userInfo.getGold(), userInfo.getStageKey(), userExtInfo.getTimezone(),
//                    userIapGiftPush.getIapGiftId(), iapGiftPush.getType(), power);
            // 通知客户端
            CsGameSystem.CSGameSystemPushGiftResponse.Builder builder = CsGameSystem.CSGameSystemPushGiftResponse.newBuilder();
            builder.putPushGift(userIapGiftPush.getIapGiftId(), userIapGiftPush.takeBuilder().build());
//            logger.info("push gift: " + Tool.protobufToJson(builder));
            JsonObject obj = ResponseUtils.getResponseData(CmdEnum.EnumCmdID.CMD_GAME_SYSTEM_PUSH_GIFT_VALUE,
                    builder.build().toByteArray());
            GameUser.pushToUser(userId, obj);
        }
    }

    /**
     * 是否累计类型的推送礼包
     */
    public static boolean isAddUpIapGiftPush(int type) {
//        if (type == IapGiftPush.TYPE_PVE_FAIL
//                || type == IapGiftPush.TYPE_ENTER_GAME
//                || type == IapGiftPush.TYPE_ENTER_SPIRITS
//                || type == IapGiftPush.TYPE_ENTER_DRAW_COUNTRY
//                || type == IapGiftPush.TYPE_ENTER_HOLY_WEAPON
//                || type == IapGiftPush.TYPE_ENTER_VESTIGE
//                || type == IapGiftPush.TYPE_ENTER_ANCIENT_STELA
//                || type == IapGiftPush.TYPE_ENTER_AWAKENED_EXPEND) {
//            return true;
//        }
        return false;
    }

    /**
     * 触发活动推送礼包
     */
    public static void checkTriggerActIapGiftPush(UserInfo userInfo, Act act, UserExtInfo userExtInfo,
                                                  List<Integer> iapGiftIdList,
                                                  List<UserIapGiftPush> userIapGiftPushList) {
        long userId = userInfo.getId();
//        if (!userInfo.checkModuleOpen(SystemOpen.MODULE_ID_IAP_GIFT_PUSH, 0)) {
//            return;
//        }
        if (iapGiftIdList == null || iapGiftIdList.isEmpty()) {
            return;
        }
        // 判断活动期间是否有礼包触发过，有则不再触发新的礼包
        boolean isTrigger = false;
        long curTime = TimeUtils.getCurTime();
        for (UserIapGiftPush userIapGiftPush : userIapGiftPushList) {
            if (!iapGiftIdList.contains(userIapGiftPush.getIapGiftId())) {
                continue;
            }
            long triggerTime = userIapGiftPush.getTriggerTime();
            if (triggerTime > 0 && triggerTime >= act.getStartTime() && triggerTime <= act.getEndTime()) {
                isTrigger = true;
                break;
            }
        }
        if (isTrigger) {
            return;
        }
        for (int i = 0; i < iapGiftIdList.size(); i++) {
            int iapGiftId = iapGiftIdList.get(i);
            IapGiftPush iapGiftPush = IapManager.getIapGiftPush(iapGiftId);
            if (iapGiftPush == null || iapGiftPush.getType() != IapGiftPush.TYPE_ACT) {
                continue;
            }
            IapGift iapGift = IapManager.getIapGift(iapGiftId);
            if (iapGift == null || iapGift.getType() != IapGift.TYPE_PUSH) {
                continue;
            }
            UserIapGiftPush userIapGiftPush = null;
            for (UserIapGiftPush model : userIapGiftPushList) {
                if (model.getIapGiftId() == iapGift.getId()) {
                    userIapGiftPush = model;
                    break;
                }
            }
            // 不在累计充值范围内
            List<Integer> chargeNumList = iapGiftPush.getChargeNumList();
            if (chargeNumList.size() >= 2) {
                if (userExtInfo.getIapBuy() < chargeNumList.get(0)
                        || userExtInfo.getIapBuy() > chargeNumList.get(1)) {
                    continue;
                }
            }

            // 不满足触发等级
            if (iapGiftPush.getLimitLevel() > 0 && userInfo.getLevel() < iapGiftPush.getLimitLevel()) {
                continue;
            }
            if (userIapGiftPush == null) {
                userIapGiftPush = new UserIapGiftPush(userId, iapGift.getId());
                userIapGiftPush.doCreate();
                userIapGiftPushList.add(userIapGiftPush);
            }

//            int triggerTime = userIapGiftPush.getTriggerTime();
//            if (triggerTime > 0 && triggerTime >= act.getStartTime() && triggerTime <= act.getEndTime()) {
//                if (userIapGiftPush.getEndTime() == 0) {
//                    continue;
//                }
//            }
            userIapGiftPush.addMainTriggerNum(1);
            userIapGiftPush.putEndTime(act.getEndTime());
            userIapGiftPush.addTriggerNum(1);
            userIapGiftPush.addTriggerNumDay(1);
            userIapGiftPush.putTriggerTime(curTime);
            userIapGiftPush.putBuyList("");
            userIapGiftPush.update();
            // 数数SDK触发推送礼包事件
//            UserTeam userTeam = TeamManager.getUserTeam(userId, UserTeam.TYPE_DEFAULT_PVE);
//            long power = userTeam == null ? 0 : userTeam.getPower();
//            ThinkingDataManager.pushPushboxTrigger(userId, userExtInfo.getDistinctId(),
//                    userInfo.getLevel(), userInfo.getVip(), userInfo.getVipScore(), userInfo.getDiamond(),
//                    userInfo.getVipGiftScore(), userInfo.getGold(), userInfo.getStageKey(), userExtInfo.getTimezone(),
//                    userIapGiftPush.getIapGiftId(), iapGiftPush.getType(), power);
            // 通知客户端
            CsGameSystem.CSGameSystemPushGiftResponse.Builder builder = CsGameSystem.CSGameSystemPushGiftResponse.newBuilder();
            builder.putPushGift(userIapGiftPush.getIapGiftId(), userIapGiftPush.takeBuilder().build());
//            logger.info("push gift: " + Tool.protobufToJson(builder));
            JsonObject obj = ResponseUtils.getResponseData(CmdEnum.EnumCmdID.CMD_GAME_SYSTEM_PUSH_GIFT_VALUE,
                    builder.build().toByteArray());
            break;
        }
    }


    /**
     * 购买免费iapGift礼包
     */
    public static Object buyFreeIapGift(int paramModule, CsGameIap.CSGameIapBuyResponse.Builder res_build,
                                        JsonObject paramObject, IapGift iapGift, UserInfo userInfo) {
        int iapGiftId = iapGift.getId();
        long userId = userInfo.getId();
        PBUserData.Builder pbUserData = res_build.getUserBuilder();
        // 日、周、月礼包,广告连锁礼包,万能活动礼包
        if (iapGift.getType() == IapGift.TYPE_DAY
                || iapGift.getType() == IapGift.TYPE_WEEK
                || iapGift.getType() == IapGift.TYPE_MONTH
                || iapGift.getType() == IapGift.TYPE_BENEFIT_AD_GIFT
                || iapGift.getType() == IapGift.TYPE_ACT_CONVENTION_GIFT
        )
        {
            if (iapGift.getLimitNum() > 0) {
                UserIapGift userIapGift = IapManager.getUserIapGift(userId, iapGiftId);
                // 超过限制数量
                if (userIapGift != null && userIapGift.getNum() >= iapGift.getLimitNum()) {
                    return ErrorWord.TIMES_LACK;
                }
                boolean isCreate = false;
                if (userIapGift == null) {
                    userIapGift = new UserIapGift(userId, iapGiftId);
                    isCreate = true;
                }
                userIapGift.addNum(1);
                if (isCreate) {
                    userIapGift.doCreate();
                } else {
                    userIapGift.update();
                }
                ProtoDataUtils.updatePBUserData(pbUserData, userIapGift);
            }
        }
        // 活动礼包
//        if (iapGift.isActIapGift()) {
//            long[] actData = MotifManager.getUserMotifActDataByIapGift(userId, iapGift);
//            // 不可购买
//            if (actData == null) {
//                return ErrorWord.NOT_DATA;
//            }
//            long actId = actData[0];
//            int subActId = (int) actData[1];
//            UserMotifIapGift userMotifIapGift = MotifManager.getUserMotifIapGift(userId, actId, subActId,
//                    iapGiftId);
//            if (iapGift.getLimitNum() > 0) {
//                // 超过限制数量
//                if (userMotifIapGift != null && userMotifIapGift.getNum() >= iapGift.getLimitNum()) {
//                    return ErrorWord.TIMES_LACK;
//                }
//            }
//            if (userMotifIapGift == null) {
//                userMotifIapGift = new UserMotifIapGift(userId, actId, subActId, iapGiftId, 1);
//                userMotifIapGift.doCreate();
//            } else {
//                userMotifIapGift.addNum(1);
//                userMotifIapGift.update();
//            }
//            // 自选礼包给自选奖励
//            if (iapGift.getType() == IapGift.TYPE_SELECT_GIFT) {
//                JsonArray selectNumAry = userMotifIapGift.getSelectNumArray();
//                JsonArray selectIndexAry = userMotifIapGift.getSelectIndexArray();
//                for (int i = 0; i < selectNumAry.size(); i++) {
//                    int selectNum = selectNumAry.getInteger(i);
//                    int selectIndex = selectIndexAry.getInteger(i);
//                    IapGiftSelect iapGiftSelect = GameDataManager.getIapGiftSelect(iapGiftId, selectNum);
//                    if (iapGiftSelect != null && iapGiftSelect.getOrderRewards().length / 2 >= selectIndex) {
//                        int[] rewards = iapGiftSelect.getOrderRewards();
//                        RewardManager.addReward(userInfo, rewards[(selectIndex - 1) * 2],
//                                rewards[(selectIndex - 1) * 2+ 1], rewardInfo, LogType.IAP_FREE_BUY, iapGiftId);
//                    }
//                }
//            }
//            res_build.setUserIapGift(userMotifIapGift.takeBuilder());
//        }
        // 每日首充礼包
//        if (iapGift.getType() == IapGift.TYPE_FIRST_CHARGE_ACT) {
//            if (iapGift.getLimitNum() > 0) {
//                UserIapGift userIapGift = GameUser.getUserIapGift(userId, iapGiftId);
//                // 超过限制数量
//                if (userIapGift != null && userIapGift.getNum() >= iapGift.getLimitNum()) {
//                    return ErrorWord.TIMES_LACK;
//                }
//                if (userIapGift == null) {
//                    userIapGift = new UserIapGift(userId, iapGiftId);
//                    userIapGift.doCreate();
//                }
//                userIapGift.addNum(1);
//                userIapGift.update();
//                res_build.setUserIapGift(userIapGift.takeBuilder());
//            }
//        }
        if (iapGift.getType() == IapGift.TYPE_PUSH) {
            IapGiftPush iapGiftPush = IapManager.getIapGiftPush(iapGift.getId());
            int relayIapGiftId = iapGiftPush.getMainIapGiftId();
            if (relayIapGiftId == 0) {
                relayIapGiftId = iapGiftId;
            }
            UserIapGiftPush userIapGiftPush = GameUser.getUserIapGiftPush(userId, relayIapGiftId);
            if (null == userIapGiftPush) {
                userIapGiftPush = new UserIapGiftPush(userId, relayIapGiftId);
                userIapGiftPush.doCreate();
            }
            if (userIapGiftPush.getEndTime() < TimeUtils.getCurTime()) {
                return ErrorWord.TIMES_LACK; // 礼包已过期
            }
            JsonArray buyList = userIapGiftPush.getBuyListArray();
            IapGiftPush mainGiftPush = IapManager.getIapGiftPush(relayIapGiftId);
            Object err = canBuyLinkGift(iapGiftId, mainGiftPush, buyList);
            if (err != null) {
                return err;
            }
            buyList.add(iapGiftId);
            userIapGiftPush.putBuyList(buyList.toString());
            List<Integer> allGifts = mainGiftPush.getSubGiftList();
            if (buyList.size() >= allGifts.size()) { // 加上主礼包本身会多出一个
                userIapGiftPush.putEndTime(TimeUtils.getCurTime());
            }
            userIapGiftPush.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userIapGiftPush);
        }

        if (iapGift.getType() == IapGift.TYPE_RECHARGE_ACT_DAILY_SPECIAL_OFFER) {
            if (iapGift.getLimitNum() > 0) {
                UserIapGift userIapGift = IapManager.getUserIapGift(userId, iapGiftId);
                // 超过限制数量
                if (userIapGift != null && userIapGift.getNum() >= iapGift.getLimitNum()) {
                    return ErrorWord.TIMES_LACK;
                }
                if (userIapGift == null) {
                    userIapGift = new UserIapGift(userId, iapGiftId);
                    userIapGift.doCreate();
                }
                userIapGift.addNum(1);
                userIapGift.update();
                ProtoDataUtils.updatePBUserData(pbUserData, userIapGift);
            }
        }
        if (iapGift.getType() == IapGift.TYPE_UNION_SCUFFLE_GIFT) {
//            Act act = ActManager.getActByType(ActConstant.ACT_TYPE_UNION_SCUFFLE, userInfo.getServerId());
//            if (act == null || !act.isStart(userInfo.getServerId())) {
//                return ErrorWord.WRONG_STATUS;
//            }
            if (!UnionScuffleManager.isDuringGame()) {
                return ErrorWord.WRONG_STATUS;
            }
            if (iapGift.getType() != IapGift.TYPE_UNION_SCUFFLE_GIFT) {
                return ErrorWord.BAD_PARAM;
            }
            UnionScuffleGift unionScuffleGift = UnionScuffleManager.getUnionScuffleGiftByIapId(iapGift.getId());
            if (unionScuffleGift == null) {
                return ErrorWord.NOT_DATA;
            }
            UserUnionScuffleGiftWeek userUnionScuffleGift = UnionScuffleManager.getUserUnionScuffleGift(userId, unionScuffleGift.getId());
            if (userUnionScuffleGift != null && userUnionScuffleGift.getBuyNum() >= unionScuffleGift.getLimitCount()) {
                return ErrorWord.ALREADY_MAX;
            }
            if (userUnionScuffleGift == null) {
                userUnionScuffleGift = new UserUnionScuffleGiftWeek(userId, unionScuffleGift.getId());
                userUnionScuffleGift.doCreate();
            } else {
                userUnionScuffleGift.addBuyNum(1);
                userUnionScuffleGift.update();
            }
            ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleGift, true);
        }
        RewardManager.addReward(userInfo, ItemId.DIAMOND, iapGift.getDiamond(), pbUserData,
                LogType.IAP_FREE_BUY, iapGiftId);
        long[] items = iapGift.getRewardArray();
        for (int i = 0; i < items.length; i += 2) {
            RewardManager.addReward(userInfo, (int) items[i], items[i + 1], pbUserData, LogType.IAP_FREE_BUY,
                    iapGiftId);
        }
        if (Tool.isInList(IapGift.RANKACT_RECHARGE_GIFTS, iapGift.getType())) {
            if (RankActManager.isLocalRankAct(userInfo)) {
                ErrorWord err = RankActManager.checkActRechargeBuy(userInfo, iapGift);
                if (null != err && err != ErrorWord.SUCCESS) {
                    return err;
                }
            } else if (RankActManager.isCrossRankAct(userInfo)) {
                ErrorWord err = RankActManager.checkCrossActRechargeBuy(userInfo, iapGift);
                if (null != err && err != ErrorWord.SUCCESS) {
                    return err;
                }
            }
            // 更新限时充值每日特惠礼包
            RankActManager.updateRechargeBuy(pbUserData, userInfo, iapGift);
            // 更新跨服限时充值每日特惠礼包
            RankActManager.updateCrossRechargeBuy(pbUserData, userInfo, iapGift);
        }

        res_build.setIapGiftId(iapGiftId);
        return res_build;
    }

    /**
     * 判断各礼包是否可购买
     */
    public static Object checkBuyIapGift(UserInfo userInfo, IapGift iapGift) {
        int iapGiftId = iapGift.getId();
        long userId = userInfo.getId();
        int[] limitLevelAry = iapGift.getLimitLevelAry();
        // 日周月礼包去掉等级判断
        if (iapGift.getType() != IapGift.TYPE_DAY
                && iapGift.getType() != IapGift.TYPE_WEEK
                && iapGift.getType() != IapGift.TYPE_MONTH) {
            if (limitLevelAry.length == 1) {
                if (userInfo.getLevel() < limitLevelAry[0]) {
                    return ErrorWord.LEVEL_LACK;
                }
            }
            if (limitLevelAry.length == 2) {
                if (userInfo.getLevel() < limitLevelAry[0] || userInfo.getLevel() > limitLevelAry[1]) {
                    return ErrorWord.LEVEL_LACK;
                }
            }
        }
        // 日周月礼包
        if (iapGift.getType() == IapGift.TYPE_DAY
                || iapGift.getType() == IapGift.TYPE_WEEK
                || iapGift.getType() == IapGift.TYPE_MONTH) {
            // 不可购买
//            if (!GameIapManager.isIapGiftDayWeekMonthBuy(iapGiftId, iapGift.getType())) {
//                return ErrorWord.NOT_DATA;
//            }
        } else if (iapGift.getType() == IapGift.TYPE_GROWTH_FUND) { // 成长基金
            int type = 0;
            int[] GROWTH_FUND = null;
            if (Tool.isInList(AllParam.GROWTH_FUND_113, iapGiftId)) {
                type = 113;
                GROWTH_FUND = AllParam.GROWTH_FUND_113;
            }
            if (Tool.isInList(AllParam.GROWTH_FUND_144, iapGiftId)) {
                type = 124;
                GROWTH_FUND = AllParam.GROWTH_FUND_144;
            }
            if (Tool.isInList(AllParam.GROWTH_FUND_184, iapGiftId)) {
                type = 184;
                GROWTH_FUND = AllParam.GROWTH_FUND_184;
            }
            if (Tool.isInList(AllParam.GROWTH_FUND_141, iapGiftId)) {
                type = 141;
                GROWTH_FUND = AllParam.GROWTH_FUND_141;
            }
            if (Tool.isInList(AllParam.GROWTH_FUND_117, iapGiftId)) {
                type = 117;
                GROWTH_FUND = AllParam.GROWTH_FUND_117;
            }
            if (type == 0) {
                return ErrorWord.NOT_DATA_1;
            } else {
                int index = IapManager.getGrowthFundGroupId(GROWTH_FUND,iapGiftId);
                // 不可购买
                if (index == 0) {
                    return ErrorWord.NOT_DATA;
                }
                UserGrowthFund userGrowthFund = IapManager.getUserGrowthFund(userId,type);
                // 重复购买
                if (userGrowthFund != null && userGrowthFund.isBuy(index)) {
                    return ErrorWord.REPEATED_OPERATION;
                }
            }
        } else if (iapGift.getType() == IapGift.TYPE_PRIVILEGE_CARD) { // 特权礼包
            int type = iapGiftId;
            UserPrivilegeCard userPrivilegeCard = IapManager.getUserPrivilegeCard(userId,type);
            if (userPrivilegeCard != null && !userPrivilegeCard.isExpired()) {
                return ErrorWord.REPEATED_OPERATION;
            }
        } else if (iapGift.getType() == IapGift.TYPE_VIP) { // Vip礼包
            Vip[] vipList = IapManager.getVipList();
            int needVipLevel = 999;//礼包所需vip等级
            for (int i = vipList.length - 1; i >= 0; i--) {
                if (vipList[i] == null) {
                    continue;
                }
                Vip vip = vipList[i];
                if (vip.getIapBuy() == iapGiftId) {
                    needVipLevel = vip.getLevel();
                }
            }
            if (needVipLevel == 999) {
                return ErrorWord.INVALID_OPERATION;
            }
            if (userInfo.getVip() < needVipLevel) {
                return ErrorWord.WRONG_STATUS;
            }
        } else if (iapGift.getType() == IapGift.TYPE_PUSH) { // 推送礼包
            IapGiftPush iapGiftPush = IapManager.getIapGiftPush(iapGiftId);
            int relayIapgiftId = iapGiftPush.getMainIapGiftId();
            if (relayIapgiftId == 0) { // 主礼包是免费礼包，肯定不会进入这个逻辑
                return ErrorWord.INVALID_OPERATION;
            }

            UserIapGiftPush userIapGiftPush = GameUser.getUserIapGiftPush(userId, relayIapgiftId);
            if (userIapGiftPush == null) {
                userIapGiftPush = new UserIapGiftPush(userId, relayIapgiftId);
                userIapGiftPush.doCreate();
            }
            if (userIapGiftPush.getEndTime() < TimeUtils.getCurTime()) {
                return ErrorWord.TIMES_LACK; // 礼包已过期
            }
            JsonArray buyList = userIapGiftPush.getBuyListArray();
            IapGiftPush mainGiftPush = IapManager.getIapGiftPush(relayIapgiftId);
            Object err = canBuyLinkGift(iapGiftId, mainGiftPush, buyList);
            if (null != err) {
                return err;
            }
        } else if (iapGift.getType() == IapGift.TYPE_FIRST_CHARGE) { // 三日首冲礼包
            if (userInfo.getIsFirstCharge() == 1) {
                return ErrorWord.REPEATED_OPERATION;
            }
        } else if (Tool.isInList(IapGift.RANKACT_RECHARGE_GIFTS, iapGift.getType())) { // 限时充值 每日特惠
            if (RankActManager.isLocalRankAct(userInfo)) {
                ErrorWord err = RankActManager.checkActRechargeBuy(userInfo, iapGift);
                if (err != null && err != ErrorWord.SUCCESS) {
                    return err;
                }
            } else if (RankActManager.isCrossRankAct(userInfo)) {
                ErrorWord err = RankActManager.checkCrossActRechargeBuy(userInfo, iapGift);
                if (err != null) {
                    return err;
                }
            } else {
                return ErrorWord.WRONG_STATUS;
            }
        } else if (iapGift.getType() == IapGift.TYPE_ACT_CONVENTION_GIFT) {
            if (!ActConventionManager.isBuyIapGift(userInfo, iapGiftId)) { // 只能在活动区间购买
                return ErrorWord.NOT_DATA;
            }
        } else if (iapGift.getType() == IapGift.TYPE_UNION_SCUFFLE_GIFT) {
//            System.out.println("buy iap " + iapGiftId);
            ErrorWord errorWord = UnionScuffleManager.checkUserUnionScuffleGift(userInfo, iapGift);
            if (errorWord != null) {
                return errorWord;
            }
        } else if (iapGift.getType() == IapGift.TYPE_UNION_SCUFFLE_PASS) {
            ErrorWord errorWord = UnionScuffleManager.checkBuyPassGift(userInfo, iapGift);
            if (errorWord != null) {
                return errorWord;
            }
        } else if (iapGift.getType() == IapGift.TYPE_RECHARGE_ACT_DAILY_SPECIAL_OFFER) {
            // 不可购买
            if (!isDailyOfferGiftBuy(userInfo, iapGift)) {
                return ErrorWord.NOT_DATA;
            }
        } else if (iapGift.getType() == IapGift.TYPE_ACT_DISCOUNT_GIFT) {  // 判断是否在活动触发时间内
            ErrorWord errorWord = OnceActManager.checkBuyGift(userInfo, iapGift);
            if (errorWord != null) {
                return errorWord;
            }
        } else if (iapGift.getType() == IapGift.TYPE_ACT_DAILY_PASS) {
            // 不可购买
            ErrorWord errorWord = ActManager.checkBuyDailyPass(userInfo, iapGift);
            if (errorWord != null) {
                return errorWord;
            }
        }
        // 礼包限购数量判断
        if (iapGift.getLimitNum() > 0 && iapGift.getType() != IapGift.TYPE_PUSH && iapGift.getType() != IapGift.TYPE_RECHARGE_ACT_DAILY_SPECIAL_OFFER
                /*&& !iapGift.isActIapGift()*/) {
            UserIapGift userIapGift = IapManager.getUserIapGift(userId, iapGiftId);
            // 超过限制数量
            if (userIapGift != null && userIapGift.getNum() >= iapGift.getLimitNum()) {
                return ErrorWord.TIMES_LACK;
            }
        }
        return ErrorWord.SUCCESS;
    }

    /**
     * 是否可购买礼包
     */
    public static Object canBuyLinkGift(int iapGiftId, IapGiftPush iapGiftPush, JsonArray buyList) {
        List<Integer> subGiftList = iapGiftPush.getSubGiftList();
        if (subGiftList.isEmpty() || !subGiftList.contains(iapGiftId)) {
            return ErrorWord.WRONG_STATUS; // 不在主礼包列表
        }
        for (Integer giftId : subGiftList) {
            if (giftId == iapGiftId) {
                break;
            }
            if (!buyList.contains(giftId)) {
                return ErrorWord.INVALID_OPERATION; // 没有购买前置礼包
            }
        }
        if (buyList.contains(iapGiftId)) { // 已买过不能重复购买
            return ErrorWord.REPEATED_OPERATION;
        }
        return null;
    }


    public static PBIapResult.Builder dealOrder(PBUserData.Builder pbUserData,long userId, JsonObject iapOrderObj, boolean isMissOrder) throws Exception {
        PBIapResult.Builder iapResultBuilder = PBIapResult.newBuilder();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);

        // 注意！！！ 当前此笔充值之前的 充值列表 (本次充值记录不会在此列表，需要含本次充值列表要重新获取)
        List<IapRecord> iapRecordList = IapManager.getIapRecordList(userId);

        String orderId = iapOrderObj.getString("order_id");
        int iapGiftId = iapOrderObj.getInteger("iap_gift_id");
        IapGift iapGift = IapManager.getIapGift(iapGiftId);
        Iap iap = IapManager.getIap(iapGift.getIapId());
        int platform = userExtInfo.getPlatform();
        long curTime = TimeUtils.getCurTime();
        boolean isFirstCharge = userExtInfo.isFirstRecharge(); // 是否是首充
        String transInfo = "";
        if (iapOrderObj.containsKey("trans_info")) {
            transInfo = iapOrderObj.getString("trans_info");
        }
        int orderDiamond = 0;
        if (iapOrderObj.containsKey("diamond")) {
            orderDiamond = iapOrderObj.getInteger("diamond");
        }
        String productId = "";
        if (iapOrderObj.containsKey("product_id")) {
            productId = iapOrderObj.getString("product_id");
        }
        boolean isFake = false; // 是否虚拟补单
        if (iapOrderObj.containsKey("is_fake")) {
            isFake = iapOrderObj.getInteger("is_fake") == 1;
        }

        // 记录有分充值钻石和普通钻石，地下城目前都是赠送元宝
        int diamond = 0; // 赠送元宝
        long[] items = iapGift.getRewardArray();
        for (int i = 0; i < items.length; i += 2) {
            if (items[i] == ItemId.DIAMOND) {
                diamond += items[i + 1];
            }
        }
//        for (Map.Entry<Integer, Long> entry : items.entrySet()) {
//            if (entry.getKey() == Item.TYPE_DIAMOND) {
//                diamond = entry.getValue().intValue();
//            }
//        }
        // 普通充值项购买 额外赠送钻石
        boolean isRechargeReset = false;// 是否有首充重置活动
        int actRechargeType = 0;// 活动充值类型 目前用于区分首充重置活动期间钻石充值和日常钻石充值
        int diamond_extra = 0;
        if (iapGift.getType() == IapGift.TYPE_DIAMOND_CHARGE) {
//            isRechargeReset = MotifManager.isMotifSubActOpen(userInfo, ActTheme.SUB_ACT_TYPE_RECHARGE_RESET);
//            if (isRechargeReset) {
//                actRechargeType = ActTheme.SUB_ACT_TYPE_RECHARGE_RESET;
//            }
            diamond_extra = getDiamondExtra(userInfo, diamond, iapGiftId, iapRecordList, isRechargeReset);
        }
        int diamond_charge = orderDiamond > 0 ? orderDiamond : iapGift.getDiamond(); // 充值钻石
        double money = iap.getBiMoney(); // 根据配置的货币类型获取金额

        // 生成充值记录
        IapRecord iapRecord = new IapRecord(userId, userInfo.getUserName(), userInfo.getServerId(), platform,
                userExtInfo.getChannel(), iapGiftId, diamond + diamond_charge + diamond_extra, productId,
                orderId, money, transInfo, isMissOrder, isFake, curTime, userInfo.getLevel(), iap.getId(),
                actRechargeType);
        iapRecord.doCreate();

        // 获得充值奖励
        // 充值钻石
        RewardManager.addReward(userInfo, ItemId.DIAMOND, diamond_charge, pbUserData, LogType.CHARGE,
                iapGiftId, iap.getId());
        // vip充值积分 -- vip积分的奖励现在填在iapGift表
        RewardManager.addReward(userInfo, ItemId.VIP_SCORE, iap.getScore(), pbUserData, LogType.CHARGE,
                iapGiftId, iap.getId());
        // 首充赠送
        RewardManager.addReward(userInfo, ItemId.DIAMOND, diamond_extra, pbUserData, LogType.CHARGE,
                iapGiftId, iap.getId());
        // 获得奖励
//        for (Map.Entry<Integer, Long> entry : items.entrySet()) {
//            RewardManager.addReward(userInfo, entry.getKey(), entry.getValue(), rewardInfo, LogType.CHARGE,
//                    iapGiftId, iap.getId());
//        }

        for (int i = 0; i < items.length; i += 2) {
            RewardManager.addReward(userInfo, (int) items[i], items[i + 1], pbUserData, LogType.CHARGE,
                    iapGiftId, iap.getId());
        }

        // 充值活动判断
        //购买钻石礼包
        updateDiamondOfCharge(userInfo, iapGift, pbUserData);
        // 成长基金
        updateGrowthFundOfCharge(userInfo, iapGift, pbUserData);
        // 特权卡
        updatePrivilegeCardOfCharge(userInfo, iapGift,pbUserData);
        //vip礼包
        updateVipOfCharge(userInfo, iapGift,pbUserData);
        // 三日首充礼包
        updateFirstChargeOfCharge(userInfo, iapGift,pbUserData);
        // 日周月重置礼包
        updateResetGiftOfCharge(userInfo, iapGift,pbUserData);
        // 百日抽
        updateHundredOfCharge(userInfo, userExtInfo, pbUserData);
        // 每日签到
        updateDailySignOfCharge(userInfo, pbUserData);
        // 每日特惠
        updateDailySpecialOfferGift(userInfo, iapGift, pbUserData);
        // 更新充值任务进度
        RankActManager.updateRechargeTask(pbUserData, userInfo, iap.getScore());
        if (Tool.isInList(IapGift.RANKACT_RECHARGE_GIFTS, iapGift.getType())) {
            // 更新限时充值每日特惠礼包
            RankActManager.updateRechargeBuy(pbUserData, userInfo, iapGift);
            // 更新跨服限时充值每日特惠礼包
            RankActManager.updateCrossRechargeBuy(pbUserData, userInfo, iapGift);
        }
        //更新联盟限时充值活动
        UnionManager.updateUnionActCharge(userInfo,iapGift,iap, pbUserData);
        // 更新活动礼包
        updateActivityGiftOfCharge(userInfo, iapGift,pbUserData);
        // 更新联盟乱斗礼包
        UnionScuffleManager.updateUserUnionScuffleGift(pbUserData, userInfo, iapGift);
        // 更新联盟乱斗通行证
        UnionScuffleManager.updatePassGift(pbUserData, userInfo, iapGift);
        // 更新主题活动累天充值
//        MotifManager.updateDayCharge(userInfo, iap.getScore());
        // 更新主题活动累计充值
//        MotifManager.updateTotalRechargeScore(userInfo, iap.getScore());
        // 更新主题活动每日好礼
//        MotifManager.updatePerDayRechargeScore(userInfo, iap.getScore());
        // 更新主题活动任务进度
//        MotifManager.updateTaskCurp(userInfo, ActThemeTask.TASK_ID_TOTAL_CHARGE, iap.getScore(), true);
        // 更新节日活动红包充值积分
//        MotifManager.updateFestivalRedPacketScore(userInfo, iap.getScore(), FestivalRedPacket.SEND_WAY_FESTIVAL);
        // 日周月礼包、时装礼包
//        updateDayWeekMonthGiftOfCharge(userId, iapGift, build);


        // 特权礼包
//        updatePrivilegeOfCharge(userInfo, iapGift, build);
        // 推送礼包
        updatePushGiftOfCharge(userInfo, iapGift, pbUserData);
        // 推送礼包
//        updatePush4GiftOfCharge(userInfo, iapGift, build);
        // 每日签到
//        updateDailySignOfCharge(userInfo);
        // 战令礼包
//        updateFightActOfCharge(userInfo, iapGift, build, rewardInfo);
        // 基金月卡
//        updateFundMonthlyOfCharge(userInfo, iapGift);
        // 主题活动礼包
//        updateMotifIapGiftOfCharge(userInfo, iapGift, build, rewardInfo);
        // 每日首充活动礼包
//        updateFirstChargeActOfCharge(userInfo, iapGift, build);
        // 经验药水礼包
//        updateExperienceOfCharge(userInfo, iapGift, build);
        // 挖矿礼包
//        updateMineOfCharge(userInfo, iapGift, build);
        // 代币礼包
//        updatePriceOfCharge(userInfo, iapGift, build);

        // 更新主题活动翻牌道具
//        MotifManager.updateMotifFlipItem(userInfo, iap.getScore(), 0, rewardInfo, LogType.CHARGE);
        // 更新节日活动源石争夺战排行榜
//        MotifManager.updateMotifPlunderRank(userInfo);

        // 更新用户充值钻石信息
        userExtInfo.charge(diamond_charge, diamond + diamond_extra, iap.getScore(), curTime);
        userExtInfo.updateQueueNow();
        ProtoDataUtils.updatePBUserData(pbUserData, userExtInfo);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_259, (long) money); // 累计充值
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_258, 1,(long) iap.getMoney()); // 购买多少个售价x以上的礼包
        if (!isFake) {

            // 设置代币的支付类型
            int itemType = iapOrderObj.getInteger("itemType", 0);// 付费道具类型
            String payType = iapOrderObj.getString("paytype", "");// 支付类型
            if (itemType == GameIapManager.IAP_BUY_TYPE_PAY_PRICE) {
                payType = PayTypeEnum.MTPAYCOIN.value;//魔兔付费代币
            } else if (itemType == GameIapManager.IAP_BUY_TYPE_MOTU_MONEY) {
                payType = PayTypeEnum.MTCOIN.value;//魔兔币
            }

            UserLoginDevice userLoginDevice = GameUser.getUserLoginDevice(userId);// 用户登录设备信息
            // 魔兔广告充值事件
            MotuAdManager.sendChargeEvent(userId, userLoginDevice, orderId, iap.getMoney());

            // 魔兔BI充值事件
            MotuBiManager.sendChargeEvent(userId, userLoginDevice, orderId, iap.getMoney(), iap.getMoneyEn(), iapGiftId, iapGift.getType(), payType);

            // 热云
            ReyunManager.sendChargeEvent(userId,userLoginDevice,orderId, iap.getMoney(),userExtInfo.getRegisterDay());

            // adjust
            AdjustManager.sendEvent(userId,userLoginDevice,AdjustManager.CHARGE,0,iap.getBiMoney());

            // 头条
            boolean isSendToutiao = true;// 是否发送头条日志
            if (AllParam.TOUTIAO_SEND_FIRST_648 == 1 && iap.isIap648() && !isTodayFirst648(iapRecordList)) {
                isSendToutiao = false;//今日第一笔648以后的大额充值，就不发送给头条了
            }
            if (isSendToutiao) {
                //注意，发送头条的金额用iap.money,人民币金额
                ToutiaoManager.sendChargeEvent(userId, userLoginDevice, iap.getMoney());
            }

            //数数SDK充值事件
            try {
                long actId = 0;
//                if (iapGift.isActIapGift()) {
                    // 活动礼包
//                    long[] actData = MotifManager.getUserMotifActDataByIapGift(userId, iapGift);
//                    if (actData != null) {
//                        actId = actData[0];
//                    }
//                }
                ThinkingDataManager.pushUserOrderEvent(userInfo, userLoginDevice, orderId,money,iapGiftId,isFirstCharge,iapGiftId,iapGift.getType(),payType,itemType,actId,iapGift.getChargeType());
            } catch (Throwable t) {
                logger.error(Tool.getException(t));
            }
            //数数SDK统计最后充值时间
            ThinkingDataManager.pushLastPayTimeData(userId, userExtInfo.getDistinctId(), curTime);
            //数数SDK用户金额累加数据
            ThinkingDataManager.pushUserIapBuyData(userId, money);

            if (isFirstCharge) {
                // 数数SDK统计用户首次充值时间数据
                ThinkingDataManager.pushFirstPayTimeData(userId, userExtInfo.getDistinctId(), curTime);
                // 首次充值事件
                AdjustManager.sendEvent(userId,userLoginDevice, AdjustManager.FIRST_CHARGE, 0);
            }
        }
        // 推送红点
//        userInfo.sendPrompt(GameConstant.PROMPT_TYPE_CHARGE, iapGift);

        // 返回客户端信息
//        build.setReward(rewardInfo.getBuild());
        iapResultBuilder.setIapId(iap.getId());
        iapResultBuilder.setIapGiftId(iapGiftId);
        iapResultBuilder.setOrderId(orderId);
        iapResultBuilder.setFirst(isFirstCharge);
        iapResultBuilder.setDiamondCharge(diamond_charge);
//        iapResultBuilder.setUserExtInfo(userExtInfo.takeBuilder());
        iapResultBuilder.setDiamond(userInfo.getDiamond());
        return iapResultBuilder;
    }

    /***
     * 判断是否为玩家当日首个648
     * @param iapRecordList
     * @return
     */
    private static boolean isTodayFirst648(List<IapRecord> iapRecordList) {
        long curTime = TimeUtils.getCurTime();
        for (IapRecord iaprecord : iapRecordList) {
            if (TimeUtils.isToday(iaprecord.getAddTime())) {
                Iap iap = IapManager.getIap(iaprecord.getIapId());
                if (iap.isIap648()) {
                    //今日已经充值过648了
                    return false;
                }
            }
        }
        return true;
    }

    /***
     * 获取VIP等级
     * @param vipScore VIP积分
     * @return VIP等级
     */
    public static int getVipLevel(int vipScore) {
        Vip[] vip = IapManager.getVipList();
        for (int i = vip.length - 1; i >= 0; i--) {
            if (vip[i] == null) {
                continue;
            }
            if (vipScore >= vip[i].getExp()) {
                return vip[i].getLevel();
            }
        }
        return 0;
    }

    /***
     * 更新VIP等级
     * @return 如果没升级则返回null
     */
    public static boolean updateVipLevel(PBUserData.Builder pbUserData,UserInfo userInfo) {
        int vipScore = userInfo.getVipScore() + userInfo.getFreeVipScore();
        byte vipLv = userInfo.getVip();
        byte newLv = (byte) getVipLevel(vipScore);
        UserLoginDevice userLoginDevice = GameUser.getUserLoginDevice(userInfo.getId());// 用户登录设备信息
        if (newLv > vipLv) {
            userInfo.putVip(pbUserData, newLv);
            userInfo.update(pbUserData);
            for (int i = vipLv + 1; i <= newLv; i++) {
                AdjustManager.sendEvent(userInfo.getId(), userLoginDevice, AdjustManager.VIP, i);// adjust VIP事件
            }
            // 数数用户Vip等级升级事件
            ThinkingDataManager.pushUserLevelUpEvent(userInfo , ThinkingDataManager.EVENT_LEVEL_UP_VIP_LEVEL, vipLv, newLv);
            return true;
        }
        return false;
    }

    /**
     * 更新userIapGfit数据
     * @param userInfo
     * @param iapGift
     * @param pbUserData
     */
    public static void updateUserIapGift(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        int iapGiftId =  iapGift.getId();
        boolean isCreate = false;
        UserIapGift userIapGift = IapManager.getUserIapGift(userId, iapGiftId);
        if (userIapGift == null) {
            userIapGift = new UserIapGift(userId, iapGiftId);
            isCreate = true;
        }
        userIapGift.addNum(1);
        if (isCreate) {
            userIapGift.doCreate();
        } else {
            userIapGift.update();
        }
        ProtoDataUtils.updatePBUserData(pbUserData, userIapGift);
    }

    /**
     * 充值更新购买钻石礼包
     */
    public static void updateDiamondOfCharge(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        if (iapGift.getType() == IapGift.TYPE_DIAMOND_CHARGE) {
            updateUserIapGift(userInfo,iapGift,pbUserData);
        }
    }

    /**
     * 充值更新购买VIP礼包
     */
    public static void updateVipOfCharge(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        if (iapGift.getType() == IapGift.TYPE_VIP) {
            updateUserIapGift(userInfo,iapGift,pbUserData);
        }
    }

    /**
     * 充值更新推送礼包数据
     */
    public static void updatePushGiftOfCharge(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        int iapGiftId = iapGift.getId();
        if (iapGift.getType() == IapGift.TYPE_PUSH) {
            IapGiftPush iapGiftPush = IapManager.getIapGiftPush(iapGiftId);
            int relayIapGiftId = iapGiftPush.getMainIapGiftId();
            if (relayIapGiftId == 0) {
                return;
            }
            IapGiftPush mainGiftPush = IapManager.getIapGiftPush(relayIapGiftId);
            UserIapGiftPush userIapGiftPush = GameUser.getUserIapGiftPush(userId, relayIapGiftId);
            if (userIapGiftPush == null) {
                userIapGiftPush = new UserIapGiftPush(userId, iapGiftId);
                userIapGiftPush.doCreate();
            }
            JsonArray buyList = userIapGiftPush.getBuyListArray();
            Object err = canBuyLinkGift(iapGiftId, mainGiftPush, buyList);
            if (err != null) {
                return;
            }
            buyList.add(iapGiftId);
            userIapGiftPush.putBuyList(buyList.toString());
            userIapGiftPush.addPushBuyNum(1);
            userIapGiftPush.addBuyNum(1);
            List<Integer> allGifts = mainGiftPush.getSubGiftList();
            if (buyList.size() >= allGifts.size()) { // 加上主礼包本身会多出一个
                userIapGiftPush.putEndTime(TimeUtils.getCurTime());
            }
            userIapGiftPush.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userIapGiftPush);
        }
    }

    /**
     * 充值更新成长基金数据
     */
    public static void updateGrowthFundOfCharge(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        int iapGiftId = iapGift.getId();
        if (iapGift.getType() == IapGift.TYPE_GROWTH_FUND) {
            int type = 0;
            int[] GROWTH_FUND = null;
            if (Tool.isInList(AllParam.GROWTH_FUND_113, iapGiftId)) {
                type = MainTaskConstant.TASK_TYPE_113;
                GROWTH_FUND = AllParam.GROWTH_FUND_113;
            }
            if (Tool.isInList(AllParam.GROWTH_FUND_144, iapGiftId)) {
                type = MainTaskConstant.TASK_TYPE_144;
                GROWTH_FUND = AllParam.GROWTH_FUND_144;
            }
            if (Tool.isInList(AllParam.GROWTH_FUND_184, iapGiftId)) {
                type = MainTaskConstant.TASK_TYPE_184;
                GROWTH_FUND = AllParam.GROWTH_FUND_184;
            }
            if (Tool.isInList(AllParam.GROWTH_FUND_141, iapGiftId)) {
                type = MainTaskConstant.TASK_TYPE_141;
                GROWTH_FUND = AllParam.GROWTH_FUND_141;
            }
            if (Tool.isInList(AllParam.GROWTH_FUND_117, iapGiftId)) {
                type = MainTaskConstant.TASK_TYPE_117;
                GROWTH_FUND = AllParam.GROWTH_FUND_117;
            }
            if (type != 0) {
                int groupId = IapManager.getGrowthFundGroupId(GROWTH_FUND,iapGiftId);
                UserGrowthFund userGrowthFund = IapManager.getUserGrowthFund(userId,type);
                boolean isCreate = false;
                if (userGrowthFund == null) {
                    userGrowthFund = new UserGrowthFund(userId, type);
                    isCreate = true;
                }
                if (userGrowthFund.setBuy(groupId)) {
                    if (isCreate) {
                        userGrowthFund.doCreate();
                    }else {
                        userGrowthFund.update();

                    }
                    ProtoDataUtils.updatePBUserData(pbUserData, userGrowthFund);
                    //红点推送
//                    userInfo.sendPrompt(GameConstant.PROMPT_TYPE_GROWTH_FUND);
                }
            } else {
                logger.error("updateGrowthFundOfCharge GROWTH_FUND = null!! error iapGiftId = " + iapGiftId + " userId:" + userId);
            }
        }
    }

    /**
     * 充值更新特权卡数据
     */
    public static void updatePrivilegeCardOfCharge(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        if (iapGift.getType() == IapGift.TYPE_PRIVILEGE_CARD) {
            long userId = userInfo.getId();
            UserPower userPower = GameUser.getUserPower(userId);
            int iapGiftId =  iapGift.getId();
            PrivilegeCard privilegeCard = IapManager.getPrivilegeCardByIapGfitId(iapGiftId);
            int privilegeCardId = privilegeCard.getId();
            UserPrivilegeCard userPrivilegeCard = IapManager.getUserPrivilegeCard(userId,privilegeCardId);
            boolean isCreate = false;
            if (userPrivilegeCard == null) {
                userPrivilegeCard = new UserPrivilegeCard(userId, privilegeCardId);
                isCreate = true;
            }
            long endTime = 0;//默认永不过期
            if (privilegeCard.getActiveTime() != 0) {
                endTime = TimeUtils.getStartTimeOfDay(TimeUtils.getCurTime()) + (long)privilegeCard.getActiveTime();
            }
            userPrivilegeCard.putEndTime(endTime);
            userPrivilegeCard.putDailyRewardTime(TimeUtils.getCurTime());
            if (isCreate) {
                userPrivilegeCard.doCreate();
            } else {
                userPrivilegeCard.update();
            }

            if (privilegeCard.getGoldNum() > 0) {// 每日可多领取num（小时）金币
                long earn = userPower.countCurrentEarn();// 玩家的城市收益,每秒
                long goldNum = earn * privilegeCard.getGoldNum() *  TimeUtils.HOUR;
                RewardManager.addReward(userInfo, ItemId.GOLD, goldNum, pbUserData, LogType.PRIVILEGE_REWARD_DAILY, privilegeCardId);
            }
            if (privilegeCard.getChildNum() > 0) {// 购买完特权卡,给所有教室增加体力
                ChildManager.addAllChildClsEnergy(pbUserData, userInfo, privilegeCard.getChildNum());
            }

            RewardManager.addReward(userInfo, ItemId.DIAMOND,privilegeCard.getDiamondNum(), pbUserData, LogType.PRIVILEGE_REWARD_DAILY, privilegeCardId);

            ProtoDataUtils.updatePBUserData(pbUserData, userPrivilegeCard);

            UserLoginDevice userLoginDevice = GameUser.getUserLoginDevice(userId);
            if (privilegeCardId == PrivilegeCardConstant.PRIVILEAGE_CARD_TYPE_1) {// 月卡
                AdjustManager.sendEvent(userInfo.getId(),userLoginDevice,AdjustManager.COMMON_MONTH_CARD, 0);
                UserPrivilegeCard userPrivilegeCard2 = IapManager.getUserPrivilegeCard(userId, PrivilegeCardConstant.PRIVILEAGE_CARD_TYPE_2);
                if (userPrivilegeCard2 != null) {
                    AdjustManager.sendEvent(userInfo.getId(),userLoginDevice,AdjustManager.BOTH_MONTH_CARD, 0);
                }
            }
            if (privilegeCardId == PrivilegeCardConstant.PRIVILEAGE_CARD_TYPE_2) {// 黄金终身卡
                AdjustManager.sendEvent(userInfo.getId(),userLoginDevice,AdjustManager.HIGH_MONTH_CARD, 0);
                UserPrivilegeCard userPrivilegeCard2 = IapManager.getUserPrivilegeCard(userId, PrivilegeCardConstant.PRIVILEAGE_CARD_TYPE_1);
                if (userPrivilegeCard2 != null) {
                    AdjustManager.sendEvent(userInfo.getId(),userLoginDevice,AdjustManager.BOTH_MONTH_CARD, 0);
                }
            }

            // 计算此时的城市收益 // 更新特权卡加成
            userPower.updateEarnAddPricard(pbUserData, userInfo);
        }
    }
    /**
     * 日周月重置礼包
     */
    public static void updateResetGiftOfCharge(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        if (iapGift.getType() == IapGift.TYPE_DAY || iapGift.getType() == IapGift.TYPE_WEEK || iapGift.getType() == IapGift.TYPE_MONTH) {
            updateUserIapGift(userInfo,iapGift,pbUserData);
        }
    }

    /**
     * 三日首充礼包
     */
    public static void updateFirstChargeOfCharge(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        if (iapGift.getType() == IapGift.TYPE_FIRST_CHARGE) {
            userInfo.putIsFirstCharge(TimeUtils.getCurTime());
            userInfo.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userInfo);
        }
    }

    /**
     * 更新活动礼包
     */
    public static void updateActivityGiftOfCharge(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        switch (iapGift.getType()) {
            case IapGift.TYPE_ACT_CONVENTION_GIFT,IapGift.TYPE_ACT_DAILY_PASS -> {
                updateUserIapGift(userInfo,iapGift,pbUserData);
            }
            case IapGift.TYPE_ACT_DISCOUNT_GIFT -> {  // 折扣礼包
                updateUserIapGift(userInfo,iapGift,pbUserData);
                UserActDiscountGift discountGiftUserData = OnceActManager.getDiscountGiftUserData(userInfo.getId());
                discountGiftUserData.putIndex(discountGiftUserData.getIndex() + 1);  // 下标自增1
                discountGiftUserData.update();
                ProtoDataUtils.updatePBUserData(pbUserData, discountGiftUserData);
            }
            case IapGift.TYPE_RECHARGE_ACT_DAILY_SPECIAL_OFFER -> {
                JsonObject param = iapGift.getParams();
                boolean isCurOneKey = param.getInteger("one_key", 0) == 1;
                if (isCurOneKey) { // 当前礼包是一键礼包
                    UserDailyRaffleDraw userDailyRaffleDraw = ActManager.getUserDailyRaffleDraw(userInfo.getId());
                    userDailyRaffleDraw.extraReward(userInfo, pbUserData);
                }
            }
        }
    }

    public static void updateDailySpecialOfferGift(UserInfo userInfo, IapGift iapGift, PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        int iapGiftId = iapGift.getId();
        if (iapGift.getType() == IapGift.TYPE_RECHARGE_ACT_DAILY_SPECIAL_OFFER) {
            //一键购买
            if (iapGift.getParams().getInteger("one_key", 0) == 1) {
                List<IapGift> iapGiftList = IapManager.getIapGiftTypeList(IapGift.TYPE_RECHARGE_ACT_DAILY_SPECIAL_OFFER);
                for (IapGift entity : iapGiftList) {
                    if (entity.getIapId() != 0 && entity.getIapId() != 999) {
                        UserIapGift userIapGift = IapManager.getUserIapGift(userInfo.getId(), entity.getId());
                        if (userIapGift == null) {
                            userIapGift = new UserIapGift(userId, entity.getId());
                            userIapGift.doCreate();
                        }
                        userIapGift.addNum(1);
                        userIapGift.update();
                        ProtoDataUtils.updatePBUserData(pbUserData, userIapGift);
                    }
                }
            } else {
                UserIapGift userIapGift = IapManager.getUserIapGift(userId, iapGiftId);
                if (userIapGift == null) {
                    userIapGift = new UserIapGift(userId, iapGiftId);
                    userIapGift.doCreate();
                }
                userIapGift.addNum(1);
                userIapGift.update();
                ProtoDataUtils.updatePBUserData(pbUserData, userIapGift);
            }
        }
    }

    public static boolean isDailyOfferGiftBuy(UserInfo userInfo, IapGift iapGift) {
        List<IapGift> iapGiftList = IapManager.getIapGiftTypeList(IapGift.TYPE_RECHARGE_ACT_DAILY_SPECIAL_OFFER);
        if (iapGiftList == null || iapGiftList.isEmpty()) {
            return false;
        }
        if (iapGift.getParams().getInteger("one_key", 0) == 1){
            for (IapGift entity : iapGiftList) {
                if (entity.getIapId() != 0  && entity.getIapId() != 999){
                    UserIapGift userIapGift = IapManager.getUserIapGift(userInfo.getId(), entity.getId());
                    if (userIapGift != null && userIapGift.getNum() >= entity.getLimitNum()){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 获取充值额外钻石数
     */
    public static int getDiamondExtra(UserInfo userInfo, int diamond, int iapGiftId, List<IapRecord> iapRecordList,
                                      boolean isRechargeReset) {
        int diamondExtra = 0;// 额外赠送钻石
        IapDiamond resultConfig = null;
        int count = 0;// iap_gift已购买次数
        count = getIapGiftBuyCount(iapGiftId, iapRecordList);
        List<IapDiamond> iapDiamondList = IapManager.getIapDiamondList(iapGiftId);
        if (iapDiamondList != null) {
            for (IapDiamond cfg : iapDiamondList) {
                // +1 是为了配合配置表 这边的count是已购买次数 配置表是第几次购买
                if (count + 1 >= cfg.getBuyTimes()) {
                    resultConfig = cfg;
                }
            }
        }
        if (resultConfig != null) {
            // getMultiple -1 是因为策划配置的是总倍数 这边功能做的是额外倍数 原有的1倍配置在iap_gift的reward字段 原本就会加上
            diamondExtra = Math.round(diamond * Math.max(resultConfig.getMultiple() - 1, 0)) + resultConfig.getGift();
        }
        return diamondExtra;
    }

    /**
     * 获取iap礼包购买次数 (日常购买钻石充值项，非首充重置活动期间)
     */
    public static int getIapGiftBuyCount(int iapGiftId, List<IapRecord> iapRecordList) {
        int count = 0;
        for (IapRecord iaprecord : iapRecordList) {
            if (iaprecord.getIapGiftId() == iapGiftId) {
                // 非首充重置活动期间的充值
                if (iaprecord.getActRechargeType() == 0) {
                    count++;
                }
            }
        }
        return count;
    }

    public static void updateHundredOfCharge(UserInfo userInfo, UserExtInfo userExtInfo, PBUserData.Builder pbUserData) {
        int loginDay = userExtInfo.getLoginDayCount();

        int[] actTenDayGift = ActManager.getActTenDayGiftInfo(userExtInfo.getRegisterTime());
        if (actTenDayGift == null || loginDay > actTenDayGift.length / 2) {
            return;
        }
        UserCommonAct userCommonAct = ActManager.getUserCommonAct(userExtInfo.getId());
        JsonArray hundredChargeArray = userCommonAct.getHundredChargeArray();
        if (!Tool.isInList(hundredChargeArray, loginDay)) {
            hundredChargeArray.add(loginDay);
            userCommonAct.putHundredCharge(hundredChargeArray.toString());
            userCommonAct.update();
            ActManager.updateHundredDraw(pbUserData, userCommonAct, userExtInfo, false);
        }
    }

    public static void updateDailySignOfCharge(UserInfo userInfo, PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        UserDailySign userDailySign = ActManager.getUserDailySign(userId);
        if (!userDailySign.isCharge()) {
            userDailySign.putIsCharge(UserDailySign.YES);
            userDailySign.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userDailySign);
        }
    }


    /**
     * 扣除魔兔币
     *
     * @param accountId 账号ID
     * @param subMoney  扣除的魔兔币
     */
    public static Future<Integer> subMotuMoney(String accountId, int subMoney, long userId, String orderid, int iapId) {
        Promise promise = Promise.promise();

        String requestUrl = ServerParam.MOTU_SDK_URL + "/submotumoney";
        JsonObject params = new JsonObject();
        params.put("gameid", ServerParam.MOTU_SDK_GAMEID);
        params.put("accid", accountId);
        params.put("money", subMoney);
        params.put("userid", userId);
        params.put("orderid", orderid);
        params.put("iapid", iapId);


        MainService.getWebClient().postAbs(requestUrl).timeout(HTTP_REQUEST_TIMEOUT).sendJsonObject(params, h -> {
            if (h.succeeded()) {
                HttpResponse<Buffer> response = h.result();
                JsonObject resObj = response.bodyAsJsonObject();
                int resultCode = resObj.getInteger("code");
                if (resultCode == 0) {
                    int money = resObj.getInteger("money");// 剩余魔兔币
                    promise.complete(Future.succeededFuture(money));
                } else {
                    logger.error("###subMotuMoney error resultCode = " + resultCode + " params = " + params.toString() + " !!!");
                    promise.complete(Future.failedFuture(String.valueOf(resultCode)));
                }
            } else {
                logger.error("###subMotuMoney error params = " + params.toString() + " cause = " + Tool.getException(h.cause()));
                promise.complete(Future.failedFuture(h.cause()));
            }
        });
        return promise.future();
    }
}
